package short

import (
	"math/rand"
	"strconv"
	errs "tacitus/library/error"
	"time"
)

var inst *Logic

func init() {
	rand.Seed(time.Now().UnixNano())
	inst = &Logic{
		CheckSumBase:    2,
		CheckSumLimit:   2,
		ObscureConstant: 64,
		ObscureBase:     2,
		ObscureDigit:    8,
	}
	inst.SetCharsString("kpohmqubwyrdtenjisvlafzgxc") // 使用打乱顺序的字母表
	inst.SetCharsString("1SsxXPparjE9yVLzm52IHDkdiuWK4MoUCA38wQOflNc6vgTFnZtJ7qbRYheB0G") // 更多字符可以生成更短的字符串，但输入会更麻烦
}

func Encode(num int64) string {
	num = inst.Obscure(num)
	num = inst.AppendCheckSum(num)
	return inst.Encode(num)
}

func Decode(str string) (int64, error) {
	num := inst.Decode(str)
	num, ok := inst.RemoveCheckSum(num)
	num = inst.UnObscure(num) // 反混淆
	if !ok {
		return num, errs.Called("校验码错误")
	}
	return num, nil
}

// 将key打乱排序
func UnSort() string {
	list := inst.Chars
	res := make([]rune, 0)
	for i:=0; i< len(inst.Chars); i++ {
		r := rand.Intn(len(list))
		res = append(res, list[r])
		list = append(list[:r], list[r+1:]...)
	}
	return string(res)
}

// 使用指定的进制显示数字
func ShowNum(num int64, base int64) string {
	if num == 0 {
		return "0"
	}
	str := ""
	for num > 0 {
		str = strconv.Itoa(int(num%base)) + str
		num = num / base
	}
	return str
}
